package com.example.statistics.ui.market

import android.content.Intent
import android.os.Bundle
import com.example.statistics.bean.*
import com.example.statistics.common.BaseInputActivity
import com.example.statistics.constant.PreferenceConstants
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.utils.AreaUtil
import com.example.statistics.utils.Constants
import com.example.statistics.weight.TextProcessingView
import com.jhj.prompt.fragment.OptionsFragment
import com.jhj.prompt.fragment.options.interfaces.OnOptionsSelectedListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MarketCustomerAddActivity : BaseInputActivity<MarketCustomerBean>() {

    private var marketCity: PreferenceArea? = null
    private var data: MarketCustomerBean? = null
    private var type: String? = null
    private var market: MarketBean? = null
    var areaName: String? = ""
    var marketName: String? = ""
    override val title: String
        get() = "市场客户"

    override val url: String
        get() = if (data == null) UrlConfig.MARKET_CUSTOMER_ADD else UrlConfig.MARKET_CUSTOMER_UPDATE

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val dialog = loadingDialog()
        GlobalScope.launch {
            data = intent.getSerializableExtra(Constants.DATA) as MarketCustomerBean?
            type = intent.getStringExtra(Constants.ACTION)
            if (data == null) { //新增
                marketCity = preferenceFind(PreferenceArea::class.java, PreferenceConstants.MARKET_CITY)
                market = preferenceFind(MarketBean::class.java, PreferenceConstants.MARKET)
                areaName = marketCity?.city.orEmpty() + marketCity?.area.orEmpty()
                if (marketCity?.province == market?.province && marketCity?.city == market?.city && marketCity?.area == market?.area) {
                    marketName = market?.market
                }
            } else {//编辑、复制
                data?.let { bean ->
                    market = MarketBean(bean.marketId, bean.province, bean.city, bean.area, bean.market, bean.position, bean.description)
                    preferenceSave(market, PreferenceConstants.MARKET)
                    if (bean.province.isNotBlank() && bean.city.isNotBlank() && bean.area.isNotBlank()) {
                        areaName = bean.city + bean.area
                        marketName = bean.market
                        //设置地点选择位置
                        areaList { provinceList, cityList, areaList ->
                            val province = provinceList.indexOfFirst { it.areaName == bean.province }
                            val city = cityList[province].indexOfFirst { it.areaName == bean.city }
                            val area = areaList[province][city].indexOfFirst { it.areaName == bean.area }
                            marketCity = PreferenceArea(province, city, area, bean.province, bean.city, bean.area)
                            preferenceSave(marketCity, PreferenceConstants.MARKET_CITY)
                        }
                    }
                }
            }
            marketInfo(market)
            withContext(Dispatchers.Main) {
                dialog.dismiss()
                initView()
                refresh()
            }
        }
    }


    override val inputDataList: List<DefineInputBean>
        get() = listOf(
            DefineInputBean(
                "地    区：", "_city", TextProcessingView.STYLE_SELECTOR_JUMPS, areaName,
                clicked = areaDialog()
            ),
            DefineInputBean(
                "市    场：", "_market", TextProcessingView.STYLE_SELECTOR_JUMPS, marketName,
                isNull = false,
                jumps = Pair(first = {
                    val intent = Intent(this, MarketInfoListActivity::class.java)
                    intent.putExtra(Constants.ACTION, Constants.SELECTOR)
                    intent.putExtra(Constants.CITY, marketCity?.city)
                    return@Pair intent
                }) { serializable, _ ->
                    (serializable as MarketBean?)?.let {
                        this.contentText = it.market
                        marketInfo(it)
                        preferenceSave(it, PreferenceConstants.MARKET)
                    }
                }
            ),
            DefineInputBean(
                "店    铺：", "shop", TextProcessingView.STYLE_INPUT, data?.shop
            ),
            DefineInputBean(
                "地    址：", "shopNumber", TextProcessingView.STYLE_INPUT, data?.shopNumber
            ),
            DefineInputBean(
                "类    别：", "attribute", TextProcessingView.STYLE_SELECTOR, data?.attribute,
                singleDialog = Pair(listOf("冻品", "鲜品", "熟食", "干调", "餐饮", "大贸", "加工厂", "其他")) { str, _ ->
                    this.contentText = str
                }
            ),
            DefineInputBean(
                "客    户：", "customer", TextProcessingView.STYLE_INPUT, data?.customer, isNull = false
            ),
            DefineInputBean(
                "电    话：", "phone", TextProcessingView.STYLE_INPUT, data?.phone, isNull = false
            ),
            DefineInputBean(
                "电    话：", "phoneOne", TextProcessingView.STYLE_INPUT, data?.phoneOne
            ),
            DefineInputBean(
                "级    别：", "level", TextProcessingView.STYLE_SELECTOR, data?.level,
                singleDialog = Pair(listOf("优质客户", "微信好友", "潜在客户", "电话待定", "跑市场客户", "其他")) { str, _ ->
                    this.contentText = str
                }
            ),
            DefineInputBean(
                "产    品：", "product", TextProcessingView.STYLE_INPUT, data?.product
            ),
            DefineInputBean(
                "备    注：", "remark", TextProcessingView.STYLE_INPUT, data?.remark
            )
        )

    private fun marketInfo(market: MarketBean?) {
        extentParams.clear()
        if (data != null && type == Constants.ACTION_EDIT) {
            extentParams.add("ID" to data?.ID?.orEmpty().toString())
        }
        extentParams.add("marketId" to market?.ID.orEmpty())
        //extentParams.add("marketCityId" to market?.marketCityId.orEmpty())
        extentParams.add("province" to market?.province.orEmpty())
        extentParams.add("city" to market?.city.orEmpty())
        extentParams.add("area" to market?.area.orEmpty())
        extentParams.add("market" to market?.market.orEmpty())
    }

    private fun areaDialog(): TextProcessingView.(Map<String, TextProcessingView>) -> Unit {
        return {
            areaList { provinceList, cityList, districtList ->
                OptionsFragment.Builder<AreaUtil.AreaNode>(this@MarketCustomerAddActivity)
                    .setLinkedPicker(provinceList, cityList, districtList)
                    .setSelectOptions(
                        marketCity?.provinceId.orEmpty(),
                        marketCity?.cityId.orEmpty(),
                        marketCity?.areaId.orEmpty()
                    )
                    .setSubmitListener(object : OnOptionsSelectedListener<AreaUtil.AreaNode> {
                        override fun onOptionsSelect(
                            options: OptionsFragment<AreaUtil.AreaNode>,
                            options1: Int?, options2: Int?, options3: Int?
                        ) {
                            val province = provinceList[options1.orEmpty()]
                            val city = cityList[options1.orEmpty()][options2.orEmpty()]
                            val area = districtList[options1.orEmpty()][options2.orEmpty()][options3.orEmpty()]
                            extentParams.clear()
                            it["market"].contentText = ""
                            contentText = city.areaName + area.areaName
                            marketCity = PreferenceArea(
                                options1, options2, options3,
                                province.areaName, city.areaName, area.areaName
                            )
                            preferenceSave(marketCity, PreferenceConstants.MARKET_CITY)
                        }
                    })
                    .show()
            }
        }
    }
}